package com.mapresso.gps;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.simplify.DouglasPeuckerLineSimplifier;


public class GpsModeler {
	
	 static GpsTrack generalizeDP(GpsTrack trackIn, double dmini) {
		GpsTrack trackOut = trackIn.copy();
		CoordinateTime[] coord = GpsUtils.path2coordTime(trackIn);
		DouglasPeuckerLineSimplifier dpls = new DouglasPeuckerLineSimplifier(coord);
		dpls.setDistanceTolerance(dmini);
		Coordinate[] coord_gen = dpls.simplify();
		String name = trackIn.meta.name;
		String desc = trackIn.meta.desc;
		String author = trackIn.meta.author;
		String email = trackIn.meta.email;
		String keywords = trackIn.meta.keywords;
		trackOut = GpsUtils.coordTime2path(coord_gen, coord);
		trackOut.meta.name = name;
		trackOut.meta.desc = desc;
		trackOut.meta.author = author;
		trackOut.meta.email = email;
		trackOut.meta.keywords = keywords;

		double dmini_meter = dmini / GpsUtils.meter2angle();
		trackOut.addDesc("DP " + GpsUtils.format(dmini_meter, 2));
		trackOut.meta.name += "_g";
		return trackOut;
	}
	 
		static GpsTrack reduceToPlausibleSpeeds(GpsTrack trackIn, double vmax) {
			GpsTrack trackOut = trackIn.copy();
			double ts = trackOut.totalSpeed();
//			if (vmax < ts) vmax = ts * 1.05;
			int j = 0;
			do {
				trackOut.doSpeeds();
				double speed_max = Double.MIN_VALUE;
				int position_max = -1;
				for (int i = 1; i < trackOut.trackPoints.size(); i++) {
					double speed_now = ((Location) trackOut.trackPoints.elementAt(i)).speed;
					if (speed_now > speed_max) {
						speed_max = speed_now;
						position_max = i;
					}
				}	
				if (speed_max < vmax) {
					if (j > 0) Log.info(j + " points removed.");
					return trackOut;
				}
				trackOut.trackPoints.remove(position_max);
				j++;
			} while (true);
		}

		static GpsTrack reduceToPlausibleSpeedsPause(GpsTrack trackIn, double vmin) {
			GpsTrack trackOut = trackIn.copy();
//			double ts = trackOut.totalSpeed();
//			if (vmin > ts) vmin = ts / 1.05;
			int j=0;
			do {
				trackOut.doSpeeds();
				trackOut.printSpeeds();
				double speed_min = Double.MAX_VALUE;
				int position_min = -1;
				for (int i = 1; i < trackOut.trackPoints.size(); i++) {
					double speed_now = ((Location) trackOut.trackPoints.elementAt(i)).speed;
					if (speed_now < speed_min) {
						speed_min = speed_now;
						position_min = i;
					}
				}	
				if (speed_min > vmin) {
					if (j > 0) Log.info(j + " points removed.");
					return trackOut;
				}
				System.out.println(position_min + ": " + speed_min);
				trackOut.removePauseTime(position_min);
				trackOut.trackPoints.remove(position_min);
				j++;
			} while (true);
		}

}
